#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Wicd support
# Copyright (c) 2011 Paulo Matias
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import dbus

class Wicd():
    def __init__(self):
        self._bus = dbus.SystemBus()
        proxy = self._bus.get_object('org.wicd.daemon', '/org/wicd/daemon')
        self._daemon = dbus.Interface(proxy, 'org.wicd.daemon')
        proxy = self._bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wireless')
        self._wireless = dbus.Interface(proxy, 'org.wicd.daemon.wireless')
    
    def scan(self):
        n = self._wireless.GetNumberOfNetworks()
        for i in xrange(n):
            ssid = str(self._wireless.GetWirelessProperty(i, 'essid'))
            bssid = str(self._wireless.GetWirelessProperty(i, 'bssid'))
            strength = int(self._wireless.GetWirelessProperty(i, 'quality'))
            yield (ssid, bssid, strength)
            
    def connect(self, ssid, bssid=None):
        n = self._wireless.GetNumberOfNetworks()
        for i in xrange(n):
            ssid_ = str(self._wireless.GetWirelessProperty(i, 'essid'))
            bssid_ = str(self._wireless.GetWirelessProperty(i, 'bssid'))
            if (bssid == bssid_) or (bssid == None and ssid == ssid_):
                self._wireless.ConnectWireless(i)
                break
            
    def current_ap(self):
        status, data = self._daemon.GetConnectionStatus()
        if int(status) != 2:
            return None
        ssid = str(data[1])
        strength = int(data[2])
        ap_id = int(data[3])
        bssid = str(self._wireless.GetWirelessProperty(ap_id, 'bssid'))
        return (ssid, bssid, strength)
            
if __name__ == '__main__':
    wicd = Wicd()
    print repr(list(wicd.scan()))
    print repr(wicd.current_ap())